﻿#include <iostream>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>
#include <typeinfo>
#include<string>
#include<QDebug>
#include "thread"

#include "armor/Inc/ArmorDector.h"
#include "utilities/Inc/general.h"
#include "utilities/Inc/opencv_extend.h"
#include "utilities/Inc/log.h"
#include "main/Inc/Phoenix.h"
#include "main/Inc/img_buffer.h"
#include"utilities/Inc/general.h"
#include"buff/Inc/Timestamp.h"
using namespace std;
using namespace cv;
Phoenix::Phoenix()
{
    sem_init(&sem_pro , 0 , 0 );
    sem_init(&sem_com , 0 , 1 );
    if(_workState ==nullptr)
    {
        _workState = make_shared<Work>();
    }
    if(_mycamera == nullptr && _mycamerabuff == nullptr)
    {
        _mycamera = make_shared<Mycamera>();
        _mycamerabuff = make_shared<Mycamera>();
    }
    bool err = _serial.InitPort();
    if(err == Serial::USB_CANNOT_FIND)
    {
        qDebug() << "USB_CANNOT_FIND";
    }
}
shared_ptr<Work> Phoenix::getWorkState()
{
    return this->_workState;

}

shared_ptr<Mycamera> Phoenix::getMyCamera()
{
    return _mycamera;
}
Mat Phoenix::getImage()
{
    return _src;
}
Phoenix::~Phoenix()
{
    cout << "~Phoenix()" << endl;
    sem_destroy(&sem_pro);
    sem_destroy(&sem_com);
}
void Phoenix::Produce()
{
    Mat src;
	//打开
    while (!_mycamera->open(1))
		;
	//设置相机参数
    while (!_mycamera->setVideoparam(MAT_WIDTH,MAT_HEIGHT,64,32,2000))
		;
	//不断读取图片
    while (!_mycamera->startStream());
	while (1)
	{
        if (!_mycamera->getVideoimage())
		{
			continue;
		}
        if (!_mycamera->rgbtocv())
        {
			continue;
		}
        src = _mycamera->getiamge();
        if(src.empty())
        {
            qDebug() << "src empty";
            continue;
        }
        sem_wait(&sem_com);
        try
        {
            _buffer.ImgEnterBuffer(src);
        }
        catch (...)
        {
            qDebug() << "照片读如出错" << endl;
            throw;
        }
        sem_post(&sem_pro);
    }
    while (!_mycamera->closeStream());
}
void Phoenix::ProduceBuff()
{
    cv::Mat src;
    //打开
    while (!_mycamerabuff->open(0))
        ;
    //设置相机参数

    while (!_mycamerabuff->setVideoparam(MAT_WIDTH,MAT_HEIGHT,64,32,2000))
        ;
    //不断读取图片
    while (!_mycamerabuff->startStream());
    while (1)
    {
        if (!_mycamerabuff->getVideoimage())
        {
            continue;
        }
        if (!_mycamerabuff->rgbtocv())
        {
            continue;
        }
        src = _mycamerabuff->getiamge();
        if(src.empty())
        {
            qDebug() << "src empty";
            continue;
        }
        if(src.empty())
        {
            qDebug() << "src empty";
            continue;
        }
        _mutex.lock();
        _src2 = src;
        _mutex.unlock();
    }
    while (!_mycamerabuff->closeStream());
}

